<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Sparklines</title>
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<link rel="stylesheet" href="../dist/uPlot.min.css">
		<style>
			th {
				text-align: right;
			}

			#heading {
				text-align: center;
				padding-bottom: 10px;
			}

			td canvas {
				display: block;
				background: pink;
			}
		</style>
	</head>
	<body>
		<script src="./lib/uDSV.iife.min.js"></script>
		<script src="../dist/uPlot.iife.js"></script>
		<table id="stocks">
			<tr>
				<th colspan="3" id="heading">Sparklines</th>
			</tr>
		</table>
		<script>
			let table = document.getElementById("stocks");

			let width = 150;
			let height = 30;

			let syms = ["AAPL","AMD","AMZN","CSCO","FB","MSFT","QCOM","SBUX","TSLA","ZNGA"];

			let parser = null;

			let proms = syms.map(sym =>
				fetch("./data/" + sym + ".csv").then(r => r.text()).then(csv => {
					parser ??= uDSV.initParser(uDSV.inferSchema(csv, { trim: true }));
					return parser.stringArrs(csv);
				})
			);

			Promise.all(proms).then(parsed => {
				let can, td;

				parsed.forEach((recs, i) => {
					let tr = document.createElement("tr");
					let th = document.createElement("th");
					th.textContent = syms[i];
					tr.appendChild(th);

					// volume
					can = makeSpark(recs, r => +r[2]);
					td  = document.createElement("td");
					td.appendChild(can);
					tr.appendChild(td);

					// close
					can = makeSpark(recs, r => +r[1].slice(1));
					td  = document.createElement("td");
					td.appendChild(can);
					tr.appendChild(td);

					table.appendChild(tr);
				});
			});

			function makeSpark(recs, yVal) {
				let x = [];
				let y = [];

				recs.forEach((r, i) => {
					x.push(i);
					y.push(yVal(r));
				});

				const opts = {
					width,
					height,
					pxAlign: false,
					cursor: {
						show: false
					},
					select: {
						show: false,
					},
					legend: {
						show: false,
					},
					scales: {
						x: {
							time: false,
						},
					},
					axes: [
						{
							show: false,
						},
						{
							show: false,
						}
					],
					series: [
						{},
						{
							stroke: "#03a9f4",
							fill: "#b3e5fc",
						},
					],
				};

				let can = new uPlot(opts, [x, y]).ctx.canvas;
				can.style.width = width + "px";
				can.style.height = height + "px";

				return can;
			}
		</script>
	</body>
</html>
